package com.hns.tool.pub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 发起http请求
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class UrlFetch {
	/**
	 * 向目标url发送消息
	 * @param url 访问url
	 * @param param 传值
	 * @return 目标地址回应的消息
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	public static BufferedReader httpPost(String url, Map<String, String> param) throws Exception {
		OutputStreamWriter writer = null;
		try {
			URL remote = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) remote.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			writer = new OutputStreamWriter(connection.getOutputStream());
			StringBuffer buff = new StringBuffer();
			for(Entry<String, String> entry : param.entrySet() ) {
				if ( buff.length() > 0 ) {
					buff.append("&");
				}
				buff.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
			}
			writer.write(buff.toString());
			writer.flush();
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				return new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			} else {
				throw new IOException("error code: " + connection.getResponseCode() + " remote: " + url);
			}
		} finally {
			if ( writer != null ) {
				writer.close();
			}
		}
	}
	
	/**
	 * 获取请求的字符串结果
	 * @param url 请求的http地址
	 * @param param 请求的参数
	 * @return 请求的字符串
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	public static String request(String url, Map<String, String> param) throws Exception {
		BufferedReader reader = null;
		try {
			reader = httpPost(url, param);
			StringBuffer sb = new StringBuffer();
			String line;
			while( (line = reader.readLine()) != null ) {
				sb.append(line);
			}
			return sb.toString();
		} finally {
			if ( reader != null ) {
				reader.close();
			}
		}
	}
	
	/**
	 * 获取请求的字符串结果（请求的信息使用json格式）
	 * @param url 请求的http地址
	 * @param json 请求的信息
	 * @return 请求的字符串
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	public static String post(String url, Object json) throws Exception {
		OutputStream writer = null;
		BufferedReader reader = null;
		try {
			URL remote = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) remote.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.addRequestProperty("Content-type", "application/json;charset=UTF-8");
			writer = connection.getOutputStream();
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(writer, json);
			writer.flush();
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				StringBuffer sb = new StringBuffer();
				String line;
				while( (line = reader.readLine()) != null ) {
					sb.append(line);
				}
				return sb.toString();
			} else {
				throw new IOException("error code: " + connection.getResponseCode() + " remote: " + url);
			}
		} finally {
			if ( writer != null ) {
				writer.close();
			}
			if ( reader != null ) {
				reader.close();
			}
		}
	}
	
}
